package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.LoginService;
import com.itheima.untils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RequestMapping("/login")
@RestController
public class LoginController {
    @Reference
    private LoginService loginService;
    @Autowired
    private JedisPool jedisPool;

    @RequestMapping("/getCode")
    public Result getCode(String telephone){
        //先生成一个4位数的验证码
        Integer code = ValidateCodeUtils.generateValidateCode(4);
        //发送验证码
        try {
            System.out.println(code);
            //SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,code.toString());
            //将验证码存入缓存中
            jedisPool.getResource().setex(telephone+ RedisMessageConstant.SENDTYPE_LOGIN,300,code.toString());
            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.SEND_VALIDATECODE_FAIL);
        }
    }

    @RequestMapping("/log")
    public Result log(@RequestBody Map map, HttpServletResponse response){
        try {
            String telephone = (String) map.get("telephone");
            String validateCode = (String) map.get("validateCode");
            //从缓存中取出验证码
            String code = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
            if (validateCode==null||!code.equals(validateCode)){
                return new Result(false,MessageConstant.VALIDATECODE_ERROR);
            }
            Member member = loginService.log(telephone);
            //把手机号存入cookie中
            Cookie cookie = new Cookie("login_member_telephone",telephone);
            cookie.setPath("/");
            cookie.setMaxAge(60*60*24*30);//30天
            response.addCookie(cookie);
            //将数据存入缓存中
            //把member转化为json
            String json = JSON.toJSON(member).toString();
            jedisPool.getResource().setex(telephone,60*30,json);
            return new Result(true, MessageConstant.LOGIN_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"登录失败");
        }
    }
}
